import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/token";
import { getLogin } from "@/api";

export const useUserStore = defineStore(
  "user",
  {
    persist: true,
    state: () => ({
      token: getToken(),
      nickName: "",
      userid: "",
    }),
    actions: {
      //登录函数
      async login (loginFrom) {
        try {
          // 登录前先清除旧数据
          this.clearAllData();
          
          const ret = await getLogin(loginFrom);
          const newToken = ret.token;
          setToken(newToken);
          this.token = newToken;
        } catch (err) {
          console.log("piniaError ===>", err)
          return Promise.reject(err)
        }
      },
      async getLoginUser () {
      },
      //退出函数
      logout () {
        removeToken();
        this.token = "";
        this.nickName = "";
        this.uid = "";
        
        // 清除所有相关数据
        this.clearAllData();
      },
      
      // 清除所有数据（包括账本数据）
      clearAllData () {
        // 清除账本数据
        try {
          const { useAccountStore } = require('@/stores/account');
          const accountStore = useAccountStore();
          if (accountStore && accountStore.clearAccount) {
            accountStore.clearAccount();
            console.log('已清除账本数据');
          }
        } catch (error) {
          console.error('清除账本数据失败:', error);
        }
      },

    },
  }
);
